package com.sunnada.edu.business.setProcess.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.sunnada.edu.business.setProcess.dao.ProcessDao;
import com.sunnada.edu.system.sysrole.service.RoleMethods;
import com.sunnada.edu.system.pub.cache.ConfigCache;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.Utils;



@Service
@Transactional
public class ProcessServiceImpl implements ProcessService {
	@Resource
	ProcessDao processDao;
	
	@Override
	public int getProcessInfoCots(HashMap<String, String> params) {
		return processDao.getProcessInfoCots(params);
	}
	@Override
	public List<?> findProcessInfo(HashMap<String, String> params) {
		return processDao.findProcessInfo(params);
	}

	@Override
	public String processDel(HashMap<String, String> params) {
		String msg = null;
		int num = processDao.processDel(params);
		if(num==0){
			msg = "删除失败!";
		}else{
			num = processDao.processInfoDel(params);
			if(num==0){
				msg = "删除失败!";
			}
		}
		return msg;
	}

	@Override
	public String processAdd(HashMap<String, String> params) {
		String msg = "";
		boolean flag = true;
		//新增或修改流程
		String processId = params.get("processId");
		int processCount = processDao.getProcessByName(params);
		if(processCount > 0){
			flag = false;
		}
		if(flag){
			if(Utils.isNull(processId)){
				processId = UUID.randomUUID().toString();
				params.put("processId", processId);
				processDao.insertProcess(params);
				msg = processId;
			}else{
				processDao.updateProcess(params);
				//删除原先入库的流程信息
				processDao.deleteProcessInfo(params);
			}
			
			//新增额每一个审批流程具体内容
			List<HashMap<String, String>> list = new ArrayList<>();
			String data = params.get("data");
			String parentId = "";
			data = data.replaceAll("“", "\"");
			data = data.replaceAll("”", "\"");
			JSONArray processData=JSONArray.parseArray(data);
		    for (int i = 0; i < processData.size(); i++) {
		    	Map<String,String> map = new HashMap<String, String>();
		    	map = (Map<String,String>)processData.get(i);
		    	String auditRecid = map.get("auditRecid");
		    	String[] auditRecids = null;
		    	if(auditRecid != null){
		    		auditRecids = auditRecid.split(",");
		    		String auditId = UUID.randomUUID().toString();
		    		for(int j = 0; j < auditRecids.length; j++){
		    			HashMap<String,String> param = new HashMap<String, String>();
		    			param.put("recId", UUID.randomUUID().toString());
		    			param.put("auditId", auditId);
		    			param.put("auditPerson", auditRecids[j]);
		    			param.put("processId", processId);
		    			param.put("loginId", params.get("loginUserId"));
		    			if(i == 0){
		    				param.put("parentId", "0");
		    			}else{
		    				param.put("parentId", parentId);
		    			}
		    			list.add(param);
		    		}
		    		parentId = auditId;
		    	}
		    	
		    }
			
			int count = processDao.insertAuditPerson(list);
			if(count == 0){
				msg = "审批流程添加失败！";
			}
		}else{
			msg = "审批流程名称重复了，请更换！";
		}
		
		return msg;
	}

	/*
	 * 判断关键字在数据库是否已经存在
	 */
	private int judgeProcessUnique(HashMap<String, String> params) {
		List<HashMap<String, String>> list = processDao.judgeProcessUnique(params);
		return list.size();
	}
	@Override
	public String processUpdate(HashMap<String, String> params) {
		String msg = "";
		int num = processDao.processUpdate(params);
		if(num==0){
			msg = "修改失败!";
		}else{
			updateprocessStatus();
		}
		return msg;
		
	}

	@Override
	public Map getProcessByRecId(HashMap<String, String> params) {
		return processDao.getProcessByRecId(params);
	}
	
	private void updateprocessStatus(){
		PubDao dao = AppContext.getInstance().getPubDao();
		String sql = "update S_DICT set rec_value = '2' where rec_key = 'process' and rec_type = 'process'";
		dao.update(sql);
	}
	
	@Override
	public List<?> getProcessList(HashMap<String, String> params) {
		return processDao.getProcessList(params);
	}
	@Override
	public List<?> getProcessPerson(HashMap<String, String> params) {
		return processDao.getProcessPerson(params);
	}
	@Override
	public int getProcessPersonCots(HashMap<String, String> params) {
		return processDao.getProcessPersonCots(params);
	}
	@Override
	public List<?> getProcessInfo(HashMap<String, String> params) {
		return processDao.getProcessInfo(params);
	}
	@Override
	public String startProcess(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		List<HashMap<String, String>> list = new ArrayList<>();
		String msg = "";
		if(params != null){
			String recId = params.get("recId");
			String processId = params.get("processId");
			String getProcessInfoSql = "select t.* from t_process_info t where  t.REC_STATUS IN ('0','1') and t.process_id = '" + processId + "'";
			List<HashMap<String, String>> processInfoList = (List<HashMap<String, String>>) dao.selectList(getProcessInfoSql);
			if(processInfoList.size() > 0){
				//插入员工发起的流程表
				for(int i = 0; i < processInfoList.size(); i++){
					HashMap<String, String> map = new HashMap<String, String>();
					map = processInfoList.get(i);
					if(("0").equals(map.get("PARENT_ID"))){
						map.put("viewFlag", "1");
					}else{
						map.put("viewFlag", "2");
					}
					map.put("recId", UUID.randomUUID().toString());
					map.put("submitId", recId);
					map.put("auditState", "3");
					map.put("taskType", "3");
					map.put("startPerson", params.get("loginUserId"));
					map.put("loginId", params.get("loginUserId"));
					map.put("applyCode", params.get("applyCode"));
					map.put("goDetailPage", params.get("goDetailPage") + "Audit");
					map.put("applyTime", params.get("applyTime"));
					list.add(map);
				}
				int num = processDao.addProcessStaff(list);
				
				if(num > 0){
					//插入员工发起流程的最终结果表
					Map<String, String> mapResult = new HashMap<String, String>();
					mapResult.put("startPerson", params.get("loginUserId"));
					mapResult.put("taskType", "1");
					mapResult.put("submitId", recId);
					mapResult.put("recId", UUID.randomUUID().toString());
					mapResult.put("processId", processId);
					mapResult.put("auditResult", "3");
					mapResult.put("applyCode", params.get("applyCode"));
					mapResult.put("goDetailPage", params.get("goDetailPage") + "View");
					mapResult.put("applyTime", params.get("applyTime"));
					mapResult.put("loginUserId", params.get("loginUserId"));
					num = processDao.addProcessResult(mapResult);
					if(num == 0){
						msg = "审批提交失败，请检查！";
					}
				}else{
					msg = "没有相应审批流程，请检查！";
				}
				
				
			}else{
				msg = "审批提交失败，请检查！";
			}
		}else{
			msg = "审批提交失败，请检查！";
		}
		return msg;
	}
	@Override
	public String getDetailPage(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String goDetailPage = "system/common/error404";
		String recId = params.get("recId");
		String taskType = params.get("taskType");
		List<Map<String, String>> list = new ArrayList<>();
		if(taskType != null){
			if(("1").equals(taskType)){
				String viewSql = "SELECT DISTINCT d.REC_VALUE FROM t_process_result t LEFT JOIN s_dict d ON t.GO_DETAIL_PAGE = d.rec_key WHERE t.SUBMIT_ID = '" + recId + "'";
				list = (List<Map<String, String>>) dao.selectList(viewSql);
				goDetailPage = list.get(0).get("REC_VALUE");
			}else{
				String auditSql = "SELECT DISTINCT d.REC_VALUE FROM t_process_staff t LEFT JOIN s_dict d ON t.GO_DETAIL_PAGE = d.rec_key WHERE t.SUBMIT_ID = '" + recId + "'";
				list = (List<Map<String, String>>) dao.selectList(auditSql);
				goDetailPage = list.get(0).get("REC_VALUE");
			}
		}
		return goDetailPage;
	}
	@Override
	public String audit(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		int num = 0;
		String auditState = params.get("auditState");
		if(("1").equals(auditState)){
			//更新流程相应阶段的状态
			num = processDao.updateAuditState(params);
			
			//更新下级的可见性
			num = processDao.updateViewFlag(params);
			
			//如果当前选择可审核通过，先判断是不是流程的最后一级，如果是更新审核的结果表
			String sql = "select t.rec_id from t_process_staff t where t.parent_id = '" + params.get("auditId") + "'";
			List<?> list = dao.selectList(sql);
			if(list.size() == 0){
				//更新流程审批结果表
				num = processDao.updateAuditResult(params);
			}
			
		}else{
			//更新流程相应阶段的状态
			num = processDao.updateAuditState(params);
			
			//如果当前选择可审核不通过，直接更新流程审批结果表
			num = processDao.updateAuditResult(params);
		}
		if(num <= 0){
			msg="审核失败！";
		}
		return msg;
	}
	@Override
	public String getProcessId(HashMap<String, String> params) {
		String processId = "";
		List<HashMap<String, String>> list = processDao.getProcessId(params);
		if(list.size() > 0){
			processId = list.get(0).get("PROCESS_ID");
		}
		return processId;
	}
	@Override
	public List<?> getProcessConditionByrecid(HashMap<String, String> params) {
		String tableName = "";
		String tableNameWorker = "";
		String processType = params.get("processType");
		if(("payrollApply").equals(processType)){
			tableName = "t_payroll_apply";
			tableNameWorker = "t_payroll_apply_worker";
		}else if(("rewardApply").equals(processType)){
			tableName = "t_reward_apply";
		}else if(("exitPayApply").equals(processType)){
			tableName = "t_exitpay_apply";
			tableNameWorker = "t_exitpay_apply_worker";
		}else if(("attendanceApply").equals(processType)){
			tableName = "t_attendance_apply";
			tableNameWorker = "t_attendance_apply_worker";
		}
		else if(("pieceApply").equals(processType)){
			tableName = "t_piece_apply";
			tableNameWorker = "t_piece_apply_worker";
		}
		params.put("tableName", tableName);
		params.put("tableNameWorker", tableNameWorker);
		if(("attendanceApply").equals(processType) || ("pieceApply").equals(processType)){
			return processDao.getProcessConditionByrecid1(params);
		}else{
			return processDao.getProcessConditionByrecid(params);
		}
	}
	@Override
	public String reject(HashMap<String, String> params) {
		String msg = "";
		String tableName = "";
		String workerTable = "";
		String processType = params.get("processType");
		if(("payRollApply").equals(processType)){
			tableName = "t_payroll_apply_worker";
			workerTable = "t_worker_salary";
		}else if(("rewardApply").equals(processType)){
			tableName = "t_reward_apply";
		}else if(("exitPayApply").equals(processType)){
			tableName = "t_exitpay_apply_worker";
			workerTable = "t_worker";
		}else if(("attendanceApply").equals(processType)){
			tableName = "t_attendance_apply_worker";
		}
		else if(("pieceApply").equals(processType)){
			tableName = "t_piece_apply_worker";
		}
		params.put("tableName", tableName);
		params.put("workerTable", workerTable);
		int num = processDao.reject(params);
		if(num == 0){
			msg = "驳回失败！";
		}else{
			if(("payRollApply").equals(processType) || ("exitPayApply").equals(processType)){
				msg = updateWorkerState(params);
			}
			
		}
		return msg;
	}
	
	/*
	 * 如果工人被驳回，修改工人表或者工人工资表状态
	 */
	private String updateWorkerState(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		String sql = "";
		if(("t_worker_salary").equals(params.get("workerTable"))){
			sql = "update " + params.get("workerTable") + " set REC_STATUS = '1' where rec_time = (select BEGIN_DATE from t_payroll_apply where rec_id = '"
					+ params.get("applyId")
					+ "') and WORKER_ID = '" + params.get("workerId") + "'";
		}else{
			sql = "update " + params.get("workerTable") + " set WORKER_STATE = '1' where REC_ID  = '" + params.get("workerId") + "'";
		}
		int num = dao.update(sql);
		if (num == 0) {
			msg = "驳回失败！";
		}
		return msg;
	}
	@Override
	public Map getNoDealWithNumber(HashMap<String, String> params) {
		return processDao.getNoDealWithNumber(params);
	}
}
